// pages/home/home.js
Page({
  data: {
    nickname: "",
    devices: [],
    hasUnreadAnnouncements: false,
  },

  onLoad: function (options) {
    console.log("Home页面onLoad");
    // 获取用户信息
    const userInfo = wx.getStorageSync("userInfo");
    console.log("存储的用户信息:", userInfo);

    if (userInfo) {
      this.setData({
        nickname: userInfo.nickname || userInfo.username,
      });

      // 获取用户昵称
      if (userInfo.userId) {
        this.getUserNickname(userInfo.userId);
      }

      // 获取设备列表，传入用户ID
      if (userInfo.userId) {
        console.log("准备获取设备列表，用户ID:", userInfo.userId);
        this.getDeviceList(userInfo.userId);
      }
    }

    // 新增：检查并保存设备信息
    const deviceInfo = wx.getStorageSync("deviceInfo");
    if (!deviceInfo) {
      this.autoSaveFirstDevice();
    }

    // 加载时就检查公告状态
    this.checkAnnouncements();
  },

  // 新增方法：自动保存第一个设备
  autoSaveFirstDevice: function () {
    const that = this;
    setTimeout(() => {
      if (that.data.devices && that.data.devices.length > 0) {
        const firstDevice = that.data.devices[0];
        console.log("自动保存第一个设备:", firstDevice);
        wx.setStorageSync("deviceInfo", {
          deviceId: firstDevice.device_id,
          deviceKey: firstDevice.device_key,
        });
      }
    }, 1500); // 等待设备列表加载完成
  },
  onShow: function (options) {
    console.log("Home页面onShow");
    // 页面显示时执行的逻辑
    // 检查是否是登录成功后跳转过来的
    const loginSuccess = wx.getStorageSync("login_success");

    // 获取设备列表
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      // 刷新用户昵称
      this.getUserNickname(userInfo.userId);

      console.log("onShow中准备获取设备列表，用户ID:", userInfo.userId);
      this.getDeviceList(userInfo.userId);

      // 检查公告
      this.checkAnnouncements();

      // 如果是登录成功跳转过来的，直接显示用户已有的设备信息
      if (loginSuccess && userInfo.devices && userInfo.devices.length > 0) {
        console.log("登录成功后显示设备列表:", userInfo.devices);

        // 处理设备数据
        const devices = userInfo.devices.map((device) => {
          return {
            device_id: device.device_id,
            device_key: device.secret, // API返回中secret对应device_key
            firmware_version: device.firmware_version || "未知",
            create_at: device.create_at || "未知",
            last_online: "未知",
            icon: "/assets/devices.png", // 使用默认图标
            status: false, // 默认状态为关闭
          };
        });

        // 设置设备列表
        this.setData({
          devices: devices,
        });

        // 清除登录成功标志
        wx.removeStorageSync("login_success");
      }
    }
  },

  // 获取用户昵称
  getUserNickname: function (userId) {
    console.log("开始获取用户昵称，用户ID:", userId);
    wx.request({
      url: "https://smartsound.top/api/v1/get_nickname",
      method: "GET",
      data: {
        user_id: userId,
      },
      success: (res) => {
        console.log("获取用户昵称响应:", res.data);
        if (res.data && res.data.code === 0 && res.data.nickname) {
          // 更新昵称
          this.setData({
            nickname: res.data.nickname,
          });

          // 更新本地存储的用户信息
          const userInfo = wx.getStorageSync("userInfo");
          if (userInfo) {
            userInfo.nickname = res.data.nickname;
            wx.setStorageSync("userInfo", userInfo);
          }
        } else {
          console.error("获取用户昵称失败:", res.data);
        }
      },
      fail: (err) => {
        console.error("获取用户昵称请求失败:", err);
      },
    });
  },

  // 获取设备列表
  getDeviceList: function (userId) {
    const app = getApp();
    console.log("开始获取设备列表API，用户ID:", userId);
    wx.request({
      url: `${app.globalData.deviceApiBaseUrl}/api/v1/get_devices`,
      method: "GET",
      data: {
        user_id: userId,
      },
      success: (res) => {
        console.log("获取设备列表响应:", res.data);
        if (res.data && res.data.code === 0 && res.data.devices) {
          // 处理设备数据，适配接口返回的数据结构
          const devices = res.data.devices.map((device) => {
            // 检查设备电源状态
            const powerState =
              device.status &&
              device.status.power &&
              device.status.power.state === "ON";

            // 获取电池电量
            const batteryLevel =
              device.status &&
              device.status.power &&
              device.status.power.battery_level
                ? device.status.power.battery_level
                : null;

            // 获取充电状态
            const chargingState =
              device.status &&
              device.status.power &&
              device.status.power.charging_state
                ? device.status.power.charging_state
                : null;

            // 获取网络状态
            const networkState =
              device.status &&
              device.status.network &&
              device.status.network.wifi_state
                ? device.status.network.wifi_state
                : null;

            // 获取音频模式
            const audioMode =
              device.status && device.status.audio && device.status.audio.mode
                ? device.status.audio.mode
                : null;

            // 获取音频效果
            const audioEffect =
              device.status && device.status.audio && device.status.audio.effect
                ? device.status.audio.effect
                : null;

            // 获取最后在线时间
            const lastOnline = device.last_online
              ? new Date(device.last_online).toLocaleString()
              : "从未在线";

            return {
              device_id: device.device_id,
              device_key: device.device_key,
              firmware_version: device.firmware_version,
              create_at: device.create_at,
              last_online: lastOnline,
              icon: "/assets/devices.png", // 使用默认图标
              status: powerState, // 设备开关状态
              battery_level: batteryLevel,
              charging_state: chargingState,
              network_state: networkState,
              audio_mode: audioMode,
              audio_effect: audioEffect,
            };
          });

          console.log("处理后的设备列表:", devices);
          this.setData({
            devices: devices,
          });
          
          // 保存第一个设备信息到缓存
          if (devices && devices.length > 0) {
            const firstDevice = devices[0];
            wx.setStorageSync("deviceInfo", {
              deviceId: firstDevice.device_id,
              deviceKey: firstDevice.device_key
            });
            console.log("已更新deviceInfo缓存:", firstDevice.device_id);
          }
        } else {
          console.error("获取设备列表接口返回错误:", res.data);
          wx.showToast({
            title: "获取设备列表失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("获取设备列表失败", err);
        wx.showToast({
          title: "获取设备列表失败",
          icon: "none",
        });
      },
    });
  },

  // 切换设备状态
  toggleDevice: function (e) {
    const deviceId = e.currentTarget.dataset.id;
    const devices = this.data.devices;
    const device = devices.find((item) => item.device_id === deviceId);

    if (device) {
      const newStatus = !device.status;

      // 更新本地状态
      const updatedDevices = devices.map((item) => {
        if (item.device_id === deviceId) {
          return { ...item, status: newStatus };
        }
        return item;
      });

      this.setData({
        devices: updatedDevices,
      });

      // 发送请求到服务器更新设备状态
      const app = getApp();
      const userInfo = wx.getStorageSync("userInfo");
      const userId = userInfo ? userInfo.userId : 0;

      // 请求数据格式必须符合后端要求
      const requestData = {
        user_id: userId,
        device_id: deviceId,
        Power_state: newStatus ? "ON" : "OFF",
        Audio: {
          effect:
            device.audio_effect &&
            ["Common", "Rock", "Jazz", "Classical"].includes(
              device.audio_effect
            )
              ? device.audio_effect
              : "Common",
          mode:
            device.audio_mode &&
            ["Sequential", "Random", "Shuffle"].includes(device.audio_mode)
              ? device.audio_mode
              : "Sequential",
        },
      };

      console.log("发送设备状态更新请求:", requestData);

      wx.request({
        url: `${app.globalData.deviceApiBaseUrl}/api/v1/change_state`,
        method: "POST",
        header: {
          "content-type": "application/json",
        },
        data: requestData,
        success: (res) => {
          console.log("设备状态更新响应:", res);
          if (res.data && res.data.code === 0) {
            wx.showToast({
              title: newStatus ? "设备已开启" : "设备已关闭",
              icon: "success",
              duration: 2000,
            });
          } else {
            console.error("设备状态更新失败:", res.data);
            wx.showToast({
              title: res.data.message || "更新设备状态失败",
              icon: "none",
            });
            // 恢复原状态
            this.setData({
              devices: devices,
            });
          }
        },
        fail: (err) => {
          console.error("更新设备状态失败", err);
          wx.showToast({
            title: "更新设备状态失败",
            icon: "none",
          });

          // 恢复原状态
          this.setData({
            devices: devices,
          });
        },
      });
    }
  },

  // 添加设备
  addDevice: function () {
    wx.navigateTo({
      url: "/pages/bind/bind",
    });
  },

  // 导航到设备详情页面
  navigateToDevice: function (e) {
    const deviceId = e.currentTarget.dataset.id;
    // 传递设备ID和设备密钥到设备页面
    const device = this.data.devices.find(
      (item) => item.device_id === deviceId
    );
    const deviceKey = device ? device.device_key : ""; // 获取设备密钥

    wx.navigateTo({
      url: `/pages/device/device?id=${deviceId}&key=${deviceKey}`,
    });
  },

  // 阻止事件冒泡
  stopPropagation: function (e) {
    e.stopPropagation();
  },

  // 跳转到公告页面
  navigateToAnnouncements: function () {
    console.log("点击公告按钮，准备跳转到公告页面");
    wx.navigateTo({
      url: "/pages/announcements/announcements",
      fail: (err) => {
        console.error("跳转到公告页面失败:", err);
        wx.showToast({
          title: "跳转失败",
          icon: "none",
        });
      },
    });
  },

  // 检查公告数量
  checkAnnouncements: function () {
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : 1; // 默认使用ID 1，如果没有用户信息

    // 使用当前时间戳作为announcement_id参数
    const id = Date.now();

    // 先清空状态
    this.setData({
      hasUnreadAnnouncements: false,
    });

    console.log("开始请求公告API...");

    wx.request({
      url: `https://smartsound.top/api/v1/user/announcements`,
      method: "GET",
      data: {
        user_id: userId,
        announcement_id: id,
      },
      success: (res) => {
        console.log("检查公告响应:", res.data);

        try {
          // 修正数据解析逻辑，适应实际API返回结构
          if (res.data && res.data.code === 0 && res.data.data) {
            const total = res.data.data.total || 0;
            console.log("未读公告数量:", total);

            // 根据API返回设置状态
            this.setData({
              hasUnreadAnnouncements: total > 0,
            });

            // 调试信息
            console.log("API返回的未读公告数量:", total);
            console.log(
              "hasUnreadAnnouncements当前值:",
              this.data.hasUnreadAnnouncements
            );
          }
        } catch (error) {
          console.error("处理公告数据错误:", error);
        }
      },
      fail: (err) => {
        console.error("检查公告失败:", err);
      },
      complete: () => {
        // 强制触发一次界面更新
        this.setData({
          forceUpdate: Date.now(),
        });

        // 额外检查
        wx.nextTick(() => {
          console.log("完成后的小红点状态:", this.data.hasUnreadAnnouncements);
        });
      },
    });
  },
});
